package org.ljy.lotterysystem.common.interceptor;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.ljy.lotterysystem.common.utils.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录拦截器
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     *  在登录前会先访问该方法
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头
        String token = request.getHeader("user_token");
        log.info("获取token={}", token);
        log.info("获取路径={}", request.getRequestURI());
        //2.解析令牌
        Claims claims = JWTUtil.parseJWT(token);
        if(claims == null) {
            log.warn("令牌解析失败");
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
